package com.sfj.system.service;

import com.kaka.starter.control.dto.ResultBean;
import com.sfj.system.dto.task.TaskReportDTO;
import com.sfj.system.properties.FileStorageProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author kaka
 * @Date 2024/04/23
 */
@Service
@Slf4j
public class UploadService {

    @Autowired
    private FileStorageProperties fileStorageProperties;

    public Object uploadFile(MultipartFile uploadFile, String type) throws IOException {
        int ran2 = (int) (Math.random() * (100 - 1) + 1);
        String fileName = "_" + getCurrentDateTime() + ran2;

        if (uploadFile.isEmpty()) {
            return ResultBean.fail("文件不能为空");
        }
        if (StringUtils.isEmpty(fileName)) {
            return ResultBean.fail("文件名不能为空");
        }
        if (StringUtils.isEmpty(type)) {
            return ResultBean.fail("文件类型不能为空");
        }

        // 原文件名
        final String originalFilename = uploadFile.getOriginalFilename();
        final String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        final String pureName = originalFilename.substring(0, originalFilename.lastIndexOf("."));

        // 构建完整文件名
        String finalFileName = pureName + fileName + suffix;

        // 获取本地存储路径
        String localPath = fileStorageProperties.getPath();

        File dir = new File(localPath + File.separator + type).getAbsoluteFile();

        log.debug(">>> DEBUG dirCandidate.getPath() = " + dir.getPath());
        log.debug(">>> DEBUG dirCandidate.getAbsolutePath() = " + dir.getAbsolutePath());
        log.debug(">>> DEBUG dirCandidate.exists() = " + dir.exists());

        if (!dir.exists()) {
            dir.mkdirs(); // 创建目录
        }

        File destFile = new File(dir, finalFileName).getAbsoluteFile();
        log.debug("destFile = " + destFile.getAbsolutePath());

        //uploadFile.transferTo(destFile);
        // 先手动输出流写入，避免容器拦截 transferTo()
        try (InputStream in = uploadFile.getInputStream();
             OutputStream out = new FileOutputStream(destFile)) {
            byte[] buffer = new byte[8192];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }

        // 构建访问地址（可按你项目的访问方式调整）
        String fileUrl = "/static/files/" + type + "/" + finalFileName;

        Map<String, Object> map = new HashMap<>();
        map.put("fileUrl", fileUrl);
        map.put("fileName", finalFileName);
        map.put("localPath", destFile.getAbsolutePath());
        System.out.println(fileUrl);
        return map;
    }

    public File download(String filePath) throws IOException {
        String basePath = fileStorageProperties.getPath();
        // 移除前缀 "/static/files/"
        String relativePath = filePath.replace("/static/files/", "");
        // 拼接实际路径
        return new File(basePath, relativePath);
    }

    private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd_HH:mm:ss");

    public static String getCurrentDateTime() {
        LocalDateTime now = LocalDateTime.now();
        return now.format(dateTimeFormatter);
    }

    public void exportXls(List<TaskReportDTO> data, Workbook workbook) {
        Sheet sheet = workbook.createSheet("督察任务表");

        // 3. 创建表头
        Row header = sheet.createRow(0);
        header.createCell(0).setCellValue("整改单位");
        header.createCell(1).setCellValue("总任务");
        header.createCell(2).setCellValue("已完成任务");
        header.createCell(3).setCellValue("未完成任务");
        header.createCell(4).setCellValue("超时任务");

        // 4. 填充数据
        for (int i = 0; i < data.size(); i++) {
            TaskReportDTO row = data.get(i);
            Row sheetRow = sheet.createRow(i + 1);
            sheetRow.createCell(0).setCellValue(row.getGroupName());
            sheetRow.createCell(1).setCellValue(row.getTotal());
            sheetRow.createCell(2).setCellValue(row.getCompleteds());
            sheetRow.createCell(3).setCellValue(row.getNoCompleteds());
            sheetRow.createCell(4).setCellValue(row.getOverdues());
        }
    }
}
